package com.blog.common.domain.adapter.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.blog.common.domain.adapter.ConvertAdapter;
import com.blog.common.domain.annotation.Convert;
import com.blog.common.domain.enums.ConvertEnums;
import com.blog.common.redis.service.RedisService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

import static com.blog.common.core.constant.CacheConstants.ENCRYPTION_BYTE;

/**
 * <p>
 * 字段加密
 * </p>
 *
 * @author Valerie
 * @date 2023/6/8
 **/
@Component
public class FieldEncryptionImpl implements ConvertAdapter {
    @Resource
    private RedisService redisService;

    @PostConstruct
    public void initKey() throws UnsupportedEncodingException {
        // 随机生成密钥
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        redisService.set(ENCRYPTION_BYTE, Base64.encode(key));
    }

    @Override
    public boolean getConvertAdapter(Convert convert) {
        return ConvertEnums.determineAdapter(convert.value(), this.getClass());
    }

    @Override
    public String convertField(Convert convert, String field) {
        boolean flag = Boolean.TRUE.equals(threadLocal.get());
        if (Boolean.TRUE.equals(flag)){
            return field;
        }
        String s = redisService.get(ENCRYPTION_BYTE).toString();
        byte[] key = Base64.decode(s);

        // 构建
        AES aes = SecureUtil.aes(key);

        // 加密为16进制表示
        String encryptHex = aes.encryptBase64(field);
        // 解密为字符串
        String decryptStr = aes.decryptStr(encryptHex, CharsetUtil.CHARSET_UTF_8);
        return field;
    }
}
